package controllers

import (
	"encoding/json"
	"fmt"
	"personal-skill/models"
	"personal-skill/util/encryptutil"
	"personal-skill/util/jwtutil"
	"personal-skill/util/resultutil"
	"strings"
)

type IndexController struct {
	BaseController
}

func (indexController *IndexController) Login() {
	user := models.User{}
	_ = json.Unmarshal(indexController.Ctx.Input.RequestBody, &user)
	err := user.GetByPwdAndUsername(encryptutil.Md5(user.Password), user.Username)
	if err != nil || user.Username == "" {
		indexController.ResponseJson(resultutil.Error(resultutil.UserNotFoundErr))
	}
	token := jwtutil.GenJwtToken(&user)
	_, _ = user.UpdateLastLoginTime()
	res := make(map[string]interface{}, 3)
	res["token"] = token
	res["userId"] = user.Id
	res["username"] = user.Username
	indexController.ResponseJson(resultutil.SuccessWithDataMsg(res, "登录成功"))
}

func (indexController *IndexController) Register() {
	username := strings.TrimSpace(indexController.GetString("username"))
	password := strings.TrimSpace(indexController.GetString("password"))
	confirmPwd := strings.TrimSpace(indexController.GetString("confirmPassword"))
	if password == "" {
		indexController.ResponseJson(resultutil.ErrorWithMsg(resultutil.UserRegisterFailErr, "密码不能为空"))
	}
	// 校验用户名是否已经被注册
	toDealUser := models.User{}
	userInDB, err := toDealUser.GetByUserName(username)
	if userInDB != nil && userInDB.Username != "" {
		indexController.ResponseJson(resultutil.Error(resultutil.UserAlreadyExistErr))
	}
	// 校验确认密码是否一致
	if password != confirmPwd {
		indexController.ResponseJson(resultutil.Error(resultutil.ConfirmPwdErr))
	}
	toDealUser.Username = username
	toDealUser.Password = encryptutil.Md5(password)
	registerId, err := toDealUser.Save()
	if err != nil || registerId < 1 {
		if err != nil {
			fmt.Println(err.Error())
		}
		indexController.ResponseJson(resultutil.Error(resultutil.UserRegisterFailErr))
	}
	indexController.ResponseJson(resultutil.SuccessWithMsg("注册成功"))
}

// ValidToken 校验token是否合法
func (indexController *IndexController) ValidToken() {
	token := indexController.GetString("token")
	validUser := jwtutil.ParseJwtToken(token)
	indexController.ResponseJson(resultutil.SuccessWithData(validUser != nil))
}
